/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.logiclander.adhocracy.httpclient;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author tim
 */
public class SSLV3ProtocolSocketFactory extends SSLProtocolSocketFactory {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    private static final String[] SSLV3_PROTOCOL = new String[]{"SSLv3"};

    @Override
    public Socket createSocket(Socket socket, String host, int port,
            boolean autoClose) throws IOException, UnknownHostException {

        SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();

        SSLSocket sslSocket = (SSLSocket) sf.createSocket(socket, host, port, autoClose);
        sslSocket.setEnabledProtocols(SSLV3_PROTOCOL);

        if (logger.isDebugEnabled()) {
            logger.debug("SSLSocket created with SSLv3 protocol enabled.");
        }

        return sslSocket;
    }

    @Override
    public Socket createSocket(String host, int port) throws IOException,
            UnknownHostException {

        SSLSocket sslSocket = (SSLSocket) super.createSocket(host, port);
        sslSocket.setEnabledProtocols(SSLV3_PROTOCOL);

        if (logger.isDebugEnabled()) {
            logger.debug("SSLSocket created with SSLv3 protocol enabled.");
        }

        return sslSocket;
    }

    @Override
    public Socket createSocket(String host, int port,
            InetAddress localAddress, int localPort) throws IOException,
            UnknownHostException {
        SSLSocket sslSocket = (SSLSocket) super.createSocket(host, port, localAddress, localPort);

        sslSocket.setEnabledProtocols(SSLV3_PROTOCOL);

        if (logger.isDebugEnabled()) {
            logger.debug("SSLSocket created with SSLv3 protocol enabled.");
        }

        return sslSocket;
    }

    @Override
    public Socket createSocket(String host, int port,
            InetAddress localAddress, int localPort,
            HttpConnectionParams params) throws IOException,
            UnknownHostException, ConnectTimeoutException {

        SSLSocket sslSocket = (SSLSocket) super.createSocket(host, port, localAddress, localPort, params);

        sslSocket.setEnabledProtocols(SSLV3_PROTOCOL);

        if (logger.isDebugEnabled()) {
            logger.debug("SSLSocket created with SSLv3 protocol enabled.");
        }

        return sslSocket;
    }
}
